package namespace.jcu.mobile.library.system;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseException;
import com.parse.ParseUser;

public class ViewHistoryActivity extends Activity{
	
	ArrayList<BookRecord> bookList;
	BookRecord bookUpdater;
	bookListAdapter bookAdapter;
	long currentTime;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Parse.initialize(this, "1GlGZQ1XWU34mHgFyDHZiZRr6HTTSWOZo2nSAowy", "GKVclKTd6TIPxLVPPbDiyvzAMoWA2XLf4ZdZYFwI");
		super.onCreate(savedInstanceState);
    	
		bookList = new ArrayList<BookRecord>();
		currentTime = System.currentTimeMillis();
		
		ParseUser currentUser = ParseUser.getCurrentUser();	//get user session
		// if user session still exists
		if(currentUser != null) 
		{
			setContentView(R.layout.insert_newbook);

		
		//parsequery to search for transactionhistory
		ParseQuery transactionQuery = new ParseQuery("TransactionRecord");
		transactionQuery.whereEqualTo("LoaneeId", ParseUser.getCurrentUser().getObjectId());	//search for query with current user id
		transactionQuery.findInBackground(new FindCallback() {
		public void done(List<ParseObject> results, ParseException e) {
			if (e == null)
			{
				//check for book loaned events and add it to booklist array when found
				for (int x = 0; x < results.size(); x++)
				{

	            	bookUpdater = new BookRecord(results.get(x).getString("BookName"), results.get(x).getCreatedAt(), "borrowed");
	            	bookList.add(bookUpdater);				
	            }
				
				//check for book returned events and add it to booklist array when found				
				for (int i =0; i < results.size(); i++)
				{

					//return book
					if (results.get(i).getBoolean("BookReturned") == true)
					{
		            	bookUpdater = new BookRecord(results.get(i).getString("BookName"), results.get(i).getUpdatedAt(), "returned");
		            	bookList.add(bookUpdater);
					}
				}
				
				//check for book renewed events and add it to booklist array when found
				for (int y = 0; y < results.size(); y++)
				{
					//renew book
					if (results.get(y).getBoolean("BookRenew") == true)
					{
		            	bookUpdater = new BookRecord(results.get(y).getString("BookName"), results.get(y).getDate("RenewDate"), "extended");
		            	bookList.add(bookUpdater);
					}
				}
				
				//sort the booklist events by their date using Comparator
				Collections.sort(bookList, new BookRecordComparator());
				
				//reverse the previous sort
				Collections.reverse(bookList);
				
				//integrating booklist array into listview
		        ListView listView = (ListView) findViewById(R.id.ListViewId);
		        listView.setAdapter(bookAdapter);
			}
		}
		});

        
        bookAdapter = new bookListAdapter(this, android.R.layout.simple_list_item_1, bookList);
		}
		
		//if user's session is not available
		else
		{
			Context context = getApplicationContext();
    		CharSequence text = "You must log in to view transaction history.";
    		int duration = Toast.LENGTH_LONG;

    		
    		//toast message to display when the item is clicked
    		Toast toast = Toast.makeText(context, text, duration);
    		toast.show();
    		
			Intent i = new Intent(ViewHistoryActivity.this, LoginActivity.class);
			startActivity(i);
		}

	}
	
	//calculate the difference between current time and inserted time
	String findTimeDifference(Date d)
	{
		
		//find the difference in long data type to be able to calculate
		long timeDifference = currentTime - d.getTime();
		Log.d("time", String.valueOf(d.getTime()));
		
		int seconds = (int)(timeDifference / 1000) % 60 ;		//find seconds
		int minutes = (int)((timeDifference / (1000*60)) % 60);		//find minutes
		int hours = (int)((timeDifference / (1000*60*60)) % 24);	//find hours
		int days = (int)((timeDifference / (1000*60*60*24)) % 365);	//find days

		
		//return output in following conditions
		if (days > 0)
		{
			if (days > 6)
			{
				
				int weeks = days/7;
				if (weeks > 4)
				{
					int months = weeks/4;
					if (months > 12)
					{
						int years = months/12;
						return String.valueOf(years)+ " years ago";
					}
					return String.valueOf(months)+ " months ago";
				}
				return String.valueOf(weeks)+ " weeks ago";
			}
			return String.valueOf(days)+ " days ago";
		}
		
		if (hours > 0)
		{
			return String.valueOf(hours)+ " hours ago";
		}
		if (minutes > 0)
		{
			return String.valueOf(minutes)+ " minutes ago";
		}
		if (seconds > 5)
		{
			return String.valueOf(seconds)+ " seconds ago";
		}
		else
		{
			return "Just now";
		}
		
	}
	
	
	
	//inner class bookListAdapter of integrating the listadapter with arrays of bookrecord
	public class bookListAdapter extends ArrayAdapter<BookRecord> {
		private ArrayList<BookRecord> bookList;

		public bookListAdapter(Context context, int textViewResourceId, ArrayList<BookRecord> bookList) {
			super(context, textViewResourceId, bookList);
			this.bookList = bookList;
		}

		//combining history_list xml into insert_newbook xml
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.history_list, null);
			}
			
			BookRecord user = bookList.get(position);
			if (user != null) {
				TextView title = (TextView) v.findViewById(R.id.title);
				TextView author = (TextView) v.findViewById(R.id.author);
				ImageView imageview = (ImageView) v.findViewById(R.id.avatar);
				
				//setting up image, relating to their events (plus-sign image for loan, minus for return, the last one for extend)
				if (user.actionType == "borrowed")
				{
					imageview.setImageResource(R.drawable.book_borrow);
				}
				else if (user.actionType == "returned")
				{
					imageview.setImageResource(R.drawable.book_return);
				}
				else if (user.actionType == "extended")
				{
					imageview.setImageResource(R.drawable.book_extend);
				}
				
					
				//set status text
				if (title != null) {
					if (user.actionType == "borrowed")
					{
						title.setText("You borrowed "+user.title+".");
					}
					else if (user.actionType == "returned")
					{
						title.setText("You returned "+user.title+".");
					}
					else if (user.actionType == "extended")
					{
						title.setText("You renewed "+user.title+".");
					}
				}
				
				//display event date
				if(author != null) {

					author.setText(findTimeDifference(user.actionDate));
				}
				
			}
			return v;
		}
	}
	
}
